package com.qk.management.web.Interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {

    //private static final String LOGIN_PATH = "/login";
    private static final String LOGIN_HEADER_NAME = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String path = request.getRequestURI();
//        boolean isLoginPath = ObjectUtil.equal(path,LOGIN_PATH);
//        if (isLoginPath){
//            return true;
//        }
        String header = request.getHeader(LOGIN_HEADER_NAME);
        if (ObjectUtil.isEmpty(header)){
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtil.parseToken(header);
            Object id = claims.get("id");
            log.info("用户id为{}",id);
            Object username = claims.get("username");
            log.info("用户名为{}",username);
            return true;
        }catch (Exception e){
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
